package com.fita.wechat.web.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.demo2do.core.web.utils.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.utils.DateFormatUtils;
import com.demo2do.core.utils.DateUtils;
import com.demo2do.core.utils.JsonUtils;
import com.fita.entity.agent.Agent;
import com.fita.entity.data.Location;
import com.fita.entity.data.Supplier;
import com.fita.entity.dto.ehi.response.LocationDetailResponse;
import com.fita.entity.dto.ehi.response.VehicleCore;
import com.fita.entity.set.Set;
import com.fita.wechat.entity.CarDetail;
import com.fita.wechat.entity.CarsSearch;
import com.fita.wechat.entity.search.CarLocationSearch;
import com.fita.wechat.entity.security.Login;
import com.fita.wechat.handler.EhiHandler;
import com.fita.wechat.service.AgentService;
import com.fita.wechat.service.CarService;
import com.fita.wechat.service.DataService;
import com.fita.wechat.service.LocationService;
import com.fita.wechat.service.SetService;
import com.fita.wechat.web.interceptor.Mobile;
import com.fita.wechat.web.interceptor.Wechat;
import com.fita.wechat.web.resolver.Secure;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * @author 宋剑宏
 *
 */
@Controller
@RequestMapping("/cars")
public class CarController {
    
    private Logger logger = LoggerFactory.getLogger(CarController.class);
    
    @Autowired
    @Qualifier("dataService")
    private DataService<Location> dataLocationService;
    
    @Autowired
    @Qualifier("dataService")
    private DataService<Supplier> supplierService;
    
    @Autowired
    private CarService carService;
    
    @Autowired
    private AgentService agentService;
    
    @Autowired
    private SetService setService;
    
    @Autowired
    private EhiHandler ehiHandler;
    
    @Autowired
    private LocationService locationService;
    
    /**
     * 查找可用车辆信息填写页面
     * 
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public ModelAndView carsSearch() {
        ModelAndView modelAndView = new ModelAndView("cars-search/cars-search");
        
        Date date = new Date();
        Date start = org.apache.commons.lang3.time.DateUtils.addDays(date, 3);
        Date end = org.apache.commons.lang3.time.DateUtils.addDays(start, 7);
        modelAndView.addObject("start", DateFormatUtils.format(start, "yyyy-MM-dd HH:mm:ss"));
        modelAndView.addObject("end", DateFormatUtils.format(end, "yyyy-MM-dd HH:mm:ss"));
        
        modelAndView.addObject("startString", DateFormatUtils.format(start, "yyyy年MM月dd日"));
        modelAndView.addObject("startTimeString", DateFormatUtils.format(start, "HH:mm"));
        modelAndView.addObject("endString", DateFormatUtils.format(end, "yyyy年MM月dd日"));
        modelAndView.addObject("endTimeString", DateFormatUtils.format(start, "HH:mm"));
        
        return modelAndView;
    }
    
    /**
     * 查找可用车辆信息结果页
     * 
     * @return
     */
    @Mobile
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
    public ModelAndView doCarsSearch(@Secure Login login, CarsSearch carsSearch) {
        
        ModelAndView modelAndView = new ModelAndView("cars-search/cars-search-result");
        
        modelAndView.addObject("carsSearch", carsSearch);
        Location pickupLocation = dataLocationService.load(Location.class, carsSearch.getPickupLocation());
        Location returnLocation = dataLocationService.load(Location.class, carsSearch.getReturnLocation());
        modelAndView.addObject("pickupLocation", pickupLocation);
        modelAndView.addObject("returnLocation", returnLocation);
        modelAndView.addObject("carsSearchString", JsonUtils.toJson(carsSearch));
        
        int days = DateUtils.daysBetween(carsSearch.getPickupDate(), carsSearch.getReturnDate());
        modelAndView.addObject("days", days);
        
        try {
            // start call handler & generate result here
            List<VehicleCore> vehicleCores = carService.searchVehicles(carsSearch);
            logger.info("doCarsSearch - [{}]", JsonUtils.toJson(vehicleCores));
            
            modelAndView.addObject("vehicleCores", vehicleCores);
            modelAndView.addObject("vehicleCoresString", JsonUtils.toJson(vehicleCores));
        } catch (BusinessException e) {
            logger.trace("search vehicle error. error is [{}]", e);
            modelAndView.setViewName("cars-search/cars-search-error");
            modelAndView.addObject("message",e.getMessage());
            modelAndView.addObject("code",e.getCode());
            return modelAndView;
        }
        
        // 获取当前代理公司
        Agent agent = agentService.load(login.getId());
        modelAndView.addObject("agentCompany", agent.getCompany());

        modelAndView.addObject("agent", agent);

        modelAndView.addObject("isLogin", true);

        return modelAndView;
    }

    /**
     * 查找可用车辆信息结果页
     *
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = {"filter", "login=false"})
    public ModelAndView doCarsSearchWithoutLogin(CarsSearch carsSearch,
                                                 HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView("cars-search/cars-search-result");

        modelAndView.addObject("carsSearch", carsSearch);
        Location pickupLocation = dataLocationService.load(Location.class, carsSearch.getPickupLocation());
        Location returnLocation = dataLocationService.load(Location.class, carsSearch.getReturnLocation());
        modelAndView.addObject("pickupLocation", pickupLocation);
        modelAndView.addObject("returnLocation", returnLocation);
        modelAndView.addObject("carsSearchString", JsonUtils.toJson(carsSearch));

        int days = DateUtils.daysBetween(carsSearch.getPickupDate(), carsSearch.getReturnDate());
        modelAndView.addObject("days", days);

        try {
            // start call handler & generate result here
            List<VehicleCore> vehicleCores = carService.searchVehicles(carsSearch);
            logger.info("doCarsSearch - [{}]", JsonUtils.toJson(vehicleCores));

            modelAndView.addObject("vehicleCores", vehicleCores);
            modelAndView.addObject("vehicleCoresString", JsonUtils.toJson(vehicleCores));
        } catch (BusinessException e) {
            logger.trace("search vehicle error. error is [{}]", e);
            modelAndView.setViewName("cars-search/cars-search-error");
            modelAndView.addObject("message",e.getMessage());
            modelAndView.addObject("code",e.getCode());
            return modelAndView;
        }

        modelAndView.addObject("isLogin", false);

        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "login"));

        return modelAndView;
    }


    /**
     * 车辆信息详情页面
     * 
     * @param id
     * @return
     */
    @Wechat
    @Mobile
    @RequestMapping(value = "/detail", method = RequestMethod.POST)
    public ModelAndView carDetail(@Secure Login login, CarDetail carDetail) {
        
        //CarDetail carDetail = JsonUtils.parse(request, CarDetail.class);
        
        ModelAndView modelAndView = new ModelAndView("cars-search/cars-search-detail");
        modelAndView.addObject("carDetail", carDetail);
        
        Location pickupLocation = dataLocationService.load(Location.class, carDetail.getPickupLocation());
        Location returnLocation = dataLocationService.load(Location.class, carDetail.getReturnLocation());
        modelAndView.addObject("pickupLocation", pickupLocation);
        modelAndView.addObject("returnLocation", returnLocation);
        modelAndView.addObject("carsDetailString", JsonUtils.toJson(carDetail));
        
        int days = DateUtils.daysBetween(carDetail.getPickupDate(), carDetail.getReturnDate());
        modelAndView.addObject("days", days);
        
        // ehiHandler 获取 地区详细信息（额外设备信息）
        Map<String, Object> params = carService.generateLocationDetailParams(carDetail);
        LocationDetailResponse locationDetail =  ehiHandler.loadLocationDetail(params);
        modelAndView.addObject("locationDetail", locationDetail);
        
        // 获取当前选择价格
        Set set = setService.load(carDetail.getSetId());
        modelAndView.addObject("set", set);
        
        // 获取当前代理公司
        Agent agent = agentService.load(login.getId());
        modelAndView.addObject("agentCompany", agent.getCompany());

        modelAndView.addObject("agent", agent);

        return modelAndView;
    }
    
    /**
     * 地区选择
     * 
     * 
     * @return
     */
    @Wechat
    @RequestMapping(value = "/locations", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult locationSearch(@RequestParam("country") String country,
                                                   @RequestParam("city") String city,
                                                   @RequestParam("supplierId") Long supplierId) {
        HttpResult httpResult = new HttpResult();
        try {
            
            Supplier supplier = supplierService.load(Supplier.class, supplierId);
            
            List<Location> locations = locationService.list(country, city, supplier.getCode());            
            httpResult.success().message("查询成功").data("locations", locations);
            
        } catch (Exception e) {
            httpResult.fail("500").message("查询失败");
        }

        return httpResult;
    }
    
    /**
     * 搜索地区
     * 
     * 
     * @return
     */
    @Wechat
    @RequestMapping(value = "/search-location", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult searchLocation(CarLocationSearch search, Page page) {
    	
        page.setEveryPage(10);
        
        HttpResult httpResult = new HttpResult();
        
        httpResult.success().message("查询成功");
        
        int totals = dataLocationService.count(Location.class, search.getPreparedFilter(false));
    	
    	if (totals > 0) {
    		
        	List<Map<String, Object>> locations = locationService.search(search, page.with(totals));
        	
        	httpResult.data("locations", locations).data("page", page);
		}
        return httpResult;
    }
    
    @Wechat
    @RequestMapping(value = "/search-hot-location", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult searchHotLocation(@RequestParam(required = true) String country, @RequestParam(required = true) String brand) {
    	
        HttpResult httpResult = new HttpResult();
        
        httpResult.success().message("查询成功");
        
        Map<String, List<Map<String, Object>>> locations = locationService.searchHotLocation(country, brand);
    	
    	httpResult.data("locations", locations);
    	
        return httpResult;
    }
    
}
